package com.kcht.itsed.mws.subscribescheduler.biz;

import com.kcht.itsed.mws.subscribescheduler.comm.*;
import com.kcht.itsed.mws.subscribescheduler.facade.IReportSenderPlugin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

@Component
@Slf4j
public class ConcreteReportSenderFactory implements IConcreteReportSenderFactory{

	private Map<String,IConcreteReportSender> reportSenderContainer = new HashMap<>();
	
	@Autowired
	@Qualifier("PollReportSender")
	private IConcreteReportSender pollReportSender;
	@Autowired
	private CachedReportSenderDecorator reportSenderDecorator;

	@Override
	public synchronized IConcreteReportSender fetchSender(String url) {
		if(reportSenderContainer.containsKey(url))return reportSenderContainer.get(url);
		else {
			IConcreteReportSender sender = generateReportSender(url);
			reportSenderContainer.put(url, sender);
			return sender;
		}
	}

	@Override
	public synchronized void retriveSender(String url) {
		reportSenderContainer.remove(url);
	}
	
	
	//处理查询字符串属性
	private Map<String,String> processUrlQueryStr(URI url) {
		Map<String,String> queryMap = new HashMap<>();
		if(url.getQuery()!=null) {
			for(String kva : url.getQuery().split("&")) {
				String[] kv = kva.split("=");
				queryMap.put(kv[0], kv[1]);
			}
		}
		return queryMap;
	}

	private IConcreteReportSender generateReportSender(String url) {
		try {
			URI uriObj = new URI(url);
			Map<String,String> queryMap = processUrlQueryStr(uriObj);

			IConcreteReportSender concreteSender;
			
			switch(uriObj.getScheme()) {
			case "http":
				concreteSender = new HttpReportSender(uriObj,queryMap);
				break;
			case "file":
				concreteSender = new LocalFileReportSender(uriObj,queryMap);
				break;
			case "plugin":
				concreteSender = generatePluginReportSender(uriObj,queryMap);
				break;
			case "poll":	//poll订阅没有缓存、压缩等装饰
				return pollReportSender;
			default:
				concreteSender = new MockReportSender("unknown scheme",url);
			}
			
			//处理压缩
			if(queryMap.containsKey("compress"))concreteSender = decorateCompress(concreteSender, queryMap.get("compress"));
			
			//处理缓存
			if(queryMap.containsKey("cache")){
				reportSenderDecorator.initContainer(url,concreteSender,Integer.parseInt(queryMap.get("cache")));
				concreteSender=reportSenderDecorator;
			}

			
			return concreteSender;

		} catch (Exception e) {
			log.error("",e);
			return new MockReportSender(e.toString(),url);
		}
	}


	private IConcreteReportSender generatePluginReportSender(URI uriObj, Map<String, String> queryMap)throws NamingException {
		//生成插件的报告发送者，从JNDI中拿出来
		String pluginJndiName = String.format("java:global/RfidMiddleware-1.00.00/%s%s!com.shhic.itsed.mws.subscribescheduler.facade.IReportSenderPlugin",
				uriObj.getAuthority(),uriObj.getPath());
		final Hashtable<String,String> jndiProperties = new Hashtable<>();
        jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
		Context context = new InitialContext(jndiProperties);
		IReportSenderPlugin senderPlugin = (IReportSenderPlugin)context.lookup(pluginJndiName);
		senderPlugin.initPlugin(queryMap);
		return senderPlugin;
	}

	//增加压缩处理装饰
	private IConcreteReportSender decorateCompress(IConcreteReportSender sender,String compressType) {
		switch(compressType) {
		case "gzip":
			return new GZipReportSenderDecorator(sender);
		}
		return sender;
	}
	
	
	

}
